<template>
    <div>
        <el-card>
            <div class="topCardBtn top-btn-container">
                <el-button
                    size="mini"
                    type="primary"
                    style="margin-right: 1rem"
                    @click="handleSave"
                >保存</el-button>
                <el-button size="mini" @click="goBack">返回</el-button>
            </div>
            <div style="display:flex">
                <el-form :model="form" :rules="rules" ref="ruleForm" style="width: 100%">
                    <el-row>
                        <el-col :span="6" style="text-align: left">
                            <el-form-item label="分部名称" prop="selectDistr">
                                <el-select
                                    placeholder="请选择分部名称"
                                    @change="handleSelectDistr"
                                    v-model="form.selectDistr"
                                >
                                    <el-option
                                        v-for="(item ,idx) in distributionList"
                                        :key="idx"
                                        :label="item.name_"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="text-align: left">
                            <el-form-item label="分项名称" prop="selectShare">
                                <el-select
                                    placeholder="请选择分项名称"
                                    @change="handleSelectShare"
                                    v-model="form.selectShare"
                                >
                                    <el-option
                                        v-for="(item ,idx) in shareList"
                                        :key="idx"
                                        :label="item.fxgcmc"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
        <el-card>
            <div style="text-align: left; margin-bottom: 1rem">
                <el-button size="mini" type="primary" @click="handleAdd('ruleForm')">新增</el-button>
                <el-button size="mini" type="primary" @click="handleUp">升级</el-button>
                <el-button size="mini" type="primary" @click="handleDown">降级</el-button>
                <el-button size="mini" type="primary" @click="setCurrent()">取消选中</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                highlight-current-row
                ref="multipleTable"
                style="width: 100%"
                @current-change="handleSelectionChange"
            >
                <!-- <el-table-column type="selection" width="55" /> -->
                <el-table-column label="序号" type="index" width="80"></el-table-column>
                <el-table-column label="任务名称" width="150" align="center">
                    <template #default="scope">
                        <el-input placeholder="请输入任务名称" v-model="scope.row.jobName" />
                    </template>
                </el-table-column>
                <el-table-column label="WBS" align="center" prop="wbs"></el-table-column>
                <!-- <el-table-column label="开放时间" align="center" prop="startTime"></el-table-column>
                <el-table-column label="结束时间" align="center" prop="endTime"></el-table-column>-->
                <el-table-column label="工期" prop="duration" align="center"></el-table-column>
                <el-table-column label="角色/工种" align="center" width="200">
                    <template #default="scope">
                        <el-select
                            @change="(val) => handleSelectRole(val, scope.$index, scope.row)"
                            v-model="scope.row.userOrTypeWork"
                            filterable
                            placeholder="请选择角色/工种"
                        >
                            <el-option
                                v-for="(role, idx) in roleList"
                                :ket="idx"
                                :label="role.name"
                                :value="role"
                            ></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="人员" prop="user" align="center"></el-table-column>
                <el-table-column label="人数" prop="peopleNumber" align="center"></el-table-column>
                <el-table-column label="前置任务" prop="predecessors" align="center"></el-table-column>
                <el-table-column label="关联表单" prop="associatedForm" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.associatedForm }}</span>
                        <el-button
                            type="text"
                            @click="handleSelectForm(scope.$index, scope.row)"
                        >选择关联表单</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="是否进度上报" align="center">
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.isProgressReport" label="上报"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="sort" prop="sort" align="center"></el-table-column> -->
            </el-table>
        </el-card>
        <!-- 关联表单 -->
        <el-dialog v-model="dialogFormVisible" title="关联表单">
            <div style="margin-bottom:1rem">
                <el-row style="width: 100%">
                    <el-col :span="10" style="display:flex;align-items:center">
                        <label style="margin-right: 1rem;width: 10rem">关联表单名称</label>
                        <el-input v-model="dialogFormName" placeholder="请输入关联表单名称"></el-input>
                    </el-col>
                    <el-col :span="3">
                        <el-button type="primary" size="mini" @click="handleGetFormData">查询</el-button>
                    </el-col>
                </el-row>
            </div>
            <div style="display: flex">
                <div style="width: 50%">
                    <h4 style="text-align: left; margin-bottom: 0.5rem;">可选数据</h4>
                    <el-table
                        :data="dialogTableData"
                        border
                        @selection-change="handleFormSelectionChange"
                    >
                        <el-table-column type="selection" width="55" />
                        <el-table-column label="序号" type="index" align="center" width="100"></el-table-column>
                        <el-table-column label="关联表单名称" prop="menu_name" align="center"></el-table-column>
                    </el-table>
                    <div style="text-align: right; margin-top: 1rem">
                        <el-pagination
                            background
                            small
                            layout="total, sizes, prev, pager, next"
                            @size-change="pageSizeChange"
                            @current-change="pageChange"
                            :current-page.sync="page"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size.sync="pagesize"
                            :total="total"
                        ></el-pagination>
                    </div>
                </div>
                <div style="width: 50%">
                    <h4 style="text-align: left; margin-bottom: 0.5rem;">已选数据</h4>
                    <el-table :data="selectTableData" border>
                        <el-table-column label="序号" type="index" align="center" width="100"></el-table-column>
                        <el-table-column label="关联表单名称" prop="menu_name" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button
                                    type="text"
                                    @click="handleDeleteSelectionData(scope.$index)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
                    <el-button size="mini" type="primary" @click="handleCommit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { reactive } from "vue"
export default {
    data() {
        return {
            distributionList: [],
            shareList: [],
            selectTableItem: [],
            total: 0,
            tableData: [],
            page: 1,
            pagesize: 10,
            form: {
                selectDistr: '',
                selectDistrId: '',
                selectShare: '',
                selectShareId: '',
            },
            rules: {
                selectDistr: [
                    {
                        required: true,
                        message: '请选择分部名称',
                        trigger: 'change',
                    },
                ],
                selectShare: [
                    {
                        required: true,
                        message: '请选择分项名称',
                        trigger: 'change',
                    },
                ],
                jobName: [
                    {
                        required: true,
                        message: '请输入任务名称',
                        trigger: 'blur',
                    },
                ]
            },
            formLabelWidth: '120px',
            roleList: [],
            dialogFormName: '',
            dialogTableData: [],
            dialogFormVisible: false,
            selectTableIndex: 0,
            childrenSort: '',
            tableIndex: 1,
            parentSort: '',
            childrenLength: 0,
            selectTableData: [],
        }
    },
    created() {
        this.getDistributionData()
    },
    methods: {
        // 查询分部名称
        getDistributionData() {
            this.$axios.post(`/form/formDefData/getList_ppcgDistribution?order=asc&offset=0&limit=10000`).then(res => {
                if (res.isOk) {
                    this.distributionList = res.rows
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择分部名称
        handleSelectDistr(val) {
            this.form.selectDistr = val.name_
            this.form.selectDistrId = val.id_
            this.form.selectShare = ''
            this.form.selectShareId = ''
            this.getShareData()
        },
        // 查询分项名称
        getShareData() {
            const param = { curPage: this.page, pageSize: this.pagesize, params: { queryData: [{ name: "master_id_", con: "like", val: this.form.selectDistrId }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgShare`, param).then(res => {
                if (res.isOk) {
                    this.shareList = res.data.list
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择分项名称
        handleSelectShare(val) {
            this.form.selectShare = val.fxgcmc
            this.form.selectShareId = val.id_
            this.getDataShare()
        },
        // 查询分项
        getDataShare() {
            const param = { curPage: this.page, pageSize: this.pagesize, params: { queryData: [{ name: "share_name_", con: "=", val: this.form.selectShare }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgScheduleTemplateMaintenanceMst`, param).then(res => {
                if (res.isOk) {
                    this.isSave = true
                    if (res.data.count > 0) {
                        this.isSave = false
                        this.$ElMessage({
                            message: `分项名称${this.form.selectShare}已存在！`,
                            type: 'error',
                        })
                    }
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 数据选中
        handleSelectionChange(val) {
            if (val?.sort) {
                console.log(val)
                this.selectedRow = val
                this.selected = true
            }
        },
        // 多选，并展示在页面
        handleFormSelectionChange(rows) {
            let data = JSON.parse(JSON.stringify(rows))
            this.selectTableData = data
        },
        // 删除多选
        handleDeleteSelectionData(index) {
            this.selectTableData.splice(index, 1)
        },
        setCurrent(row) {
            row = ''
            this.selectedRow = ''
            this.selected = false
            this.$refs.multipleTable.setCurrentRow(row)
        },
        // 新增
        handleAdd(formName) {
            if (!this.form.selectShare) {
                this.$ElMessage({
                    message: `请选择分部分项`,
                    type: 'warning',
                })
                return
            } else if (!this.isSave) {
                this.$ElMessage({
                    message: `分项名称${this.form.selectShare}已存在！`,
                    type: 'error',
                })
                return
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.selected) {
                        let wbs = this.selectedRow.wbs + '.' + (this.selectedRow.children + 1)
                        let index = 0
                        for (let i = 0; i < this.tableData.length; i++) {
                            if (this.selectedRow.wbs === this.tableData[i].wbs) {
                                index = i
                                break
                            }
                        }
                        index++
                        this.tableData.splice(index + this.selectedRow.children, 0, { parentSort: this.parentSort, sort: this.selectedRow.sort, wbs, children: 0, parentId: this.selectedRow.wbs })
                        this.selectedRow.children += 1
                    } else {
                        let index = this.tableData.length > 0 ? this.tableData.length - 1 : 0
                        let sort = this.tableData.length > 0 ? this.tableData[index].sort + 1 : 1
                        this.tableData.push({ sort, wbs: sort, children: 0, parentId: 0 })
                    }
                    this.tableData = this.tableData.sort((a, b) => Number(a.wbs) - Number(b.wbs))
                    this.getRoleData()
                }
            })
        },
        // 编辑
        handleEdit() {

        },
        // 删除
        handleDelete(index, row) {
            this.$ElMessageBox.confirm(
                '确定删除该条数据吗？',
                '警告',
                {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                let childrenCount = 1
                let wbsArr = '', firstWbs = '', wbs = ''
                let tableLength = this.tableData.length

                // 获取选中数据父级的父级
                let selectParentIndex = this.tableData.findIndex(function (item) {
                    return item.wbs === row.parentId
                });
                // 处理选中数据之后的数据
                for (let i = index + 1; i < tableLength; i++) {
                    // 判断有没有子级，有子级-1
                    if (selectParentIndex < 0) {
                        selectParentIndex = index
                    }
                    if (!this.tableData[i].parentId && !row.parentId) {
                        this.tableData[i].wbs -= 1
                        this.tableData[i].sort = this.tableData[i].sort - 1
                    } else if (this.tableData[selectParentIndex].wbs === this.tableData[i].parentId) {
                        wbsArr = this.tableData[i].wbs.toString().split('.')
                        firstWbs = (wbsArr.splice(0, wbsArr.length - 1)).toString().replaceAll(',', '.') // 父节点除最后一位保存起来
                        wbs = Number(wbsArr.splice(wbsArr.length - 1, 1))
                        wbs -= 1
                        this.tableData[i].wbs = (firstWbs ? firstWbs + '.' : '') + (wbs != 0 ? wbs : '')
                    }
                }
                // 选择第一节点删除，同时删除所有子节点
                childrenCount += Number(this.tableData[index].children)
                if (this.tableData[index].parentId && selectParentIndex >= 0) {
                    this.tableData[selectParentIndex].children = this.tableData[selectParentIndex].children > 0 ? this.tableData[selectParentIndex].children - 1 : 0
                }
                this.tableData.splice(index, childrenCount)

                // 重新按照wbs排序
                this.tableData = this.tableData.sort((a, b) => a.wbs - b.wbs)
                this.setCurrent(row)
            })
        },
        // 升级
        handleUp() {
            let selectRowIndex = 0, wbsArr = '', firstWbs = '', wbs = ''
            let tableLength = this.tableData.length
            let selectedWbs = this.selectedRow.wbs
            // 获取选中数据索引
            selectRowIndex = this.tableData.findIndex(function (item) {
                return item.wbs === selectedWbs;
            });
            // 获取选中数据父级的父级
            let that = this
            let selectParentIndex = this.tableData.findIndex(function (item) {
                return item.wbs === that.selectedRow.parentId
            });
            // 处理选中数据
            if (this.tableData[selectRowIndex].parentId) {
                wbsArr = this.tableData[selectRowIndex].parentId.toString().split('.')
                firstWbs = (wbsArr.splice(0, wbsArr.length - 1)).toString().replaceAll(',', '.') // 父节点除最后一位保存起来
                wbs = Number(wbsArr.splice(wbsArr.length - 1, 1))
                wbs += 1
                this.tableData[selectRowIndex].wbs = (firstWbs ? firstWbs + '.' : '') + wbs
                this.tableData[selectRowIndex].parentId = this.tableData[selectParentIndex].parentId
                this.tableData[selectRowIndex].sort = this.tableData[selectRowIndex].sort + 1
                this.tableData[selectParentIndex].children--
            }
            // 处理选中数据之后的数据
            for (let i = selectRowIndex + 1; i < tableLength; i++) {
                // 如果没有parentId证明该wbs为第一级，直接+1
                if (!this.tableData[i].parentId && !this.tableData[selectRowIndex].parentId) {
                    this.tableData[i].wbs = this.tableData[i].sort + 1
                    this.tableData[i].sort = this.tableData[i].sort + 1
                } else if (this.tableData[selectParentIndex].wbs === this.tableData[i].parentId) {
                    // 处理子级
                    wbsArr = this.tableData[i].wbs.toString().split('.')
                    firstWbs = (wbsArr.splice(0, wbsArr.length - 1)).toString().replaceAll(',', '.') // 父节点除最后一位保存起来
                    wbs = Number(wbsArr.splice(wbsArr.length - 1, 1))
                    wbs -= 1
                    this.tableData[i].wbs = (firstWbs ? firstWbs + '.' : '') + wbs
                    this.tableData[i].parentId = this.tableData[selectParentIndex].parentId
                    this.tableData[i].sort = this.tableData[selectRowIndex].sort + 1
                }
            }
            // 重新按照wbs排序
            this.tableData = this.tableData.sort((a, b) => a.wbs - b.wbs)
            this.setCurrent(this.selectedRow)
        },
        // 降级
        handleDown() {
            let selectRowIndex = 0
            let tableLength = this.tableData.length
            let selectedWbs = this.selectedRow.wbs
            // 获取选中数据索引
            selectRowIndex = this.tableData.findIndex(function (item) {
                return item.wbs === selectedWbs;
            });
            // 处理所选数据-1
            if (selectRowIndex > 0) {
                // 处理选中数据之后的数据
                for (let i = selectRowIndex + 1; i < tableLength; i++) {
                    // 如果没有parentId证明该wbs为第一级，直接-1
                    if (!this.tableData[i].parentId && !this.tableData[selectRowIndex].parentId) {
                        this.tableData[i].wbs = this.tableData[i].wbs - 1
                        this.tableData[i].sort = this.tableData[i].sort - 1
                        this.tableData[i].parentId = this.tableData[selectRowIndex].parentId
                    } else if (this.tableData[selectRowIndex].wbs === this.tableData[i].parentId) {
                        // 处理子级
                        this.tableData[i].parentId = this.tableData[selectRowIndex - 1].wbs + '.' + (this.tableData[selectRowIndex - 1].children + 1)
                        this.tableData[i].wbs = this.tableData[i].parentId + '.' + this.tableData[selectRowIndex].children
                        this.tableData[i].sort--
                    }
                }
                this.tableData[selectRowIndex].wbs = this.tableData[selectRowIndex - 1].wbs + '.' + (this.tableData[selectRowIndex - 1].children + 1)
                this.tableData[selectRowIndex].parentId = this.tableData[selectRowIndex - 1].wbs
                this.tableData[selectRowIndex].sort--
                this.tableData[selectRowIndex - 1].children++
            }

            // 重新按照wbs排序
            this.tableData = this.tableData.sort((a, b) => a.wbs - b.wbs)
            this.setCurrent(this.selectedRow)
        },
        goBack() {
            this.$router.go(-1)
        },
        // 页码变更
        pageChange(val) {
            this.page = Number(val) * Number(this.pagesize);
            this.handleGetFormData();
        },
        // 条目变更
        pageSizeChange(val) {
            this.pagesize = val;
            this.handleGetFormData();
        },
        // showSelectFormDialog(index, item) {
        //     this.dialogFormVisible = true
        //     this.selectTableIndex = index
        //     this.dialogFormName = ''
        //     this.handleGetFormData()
        // },
        // 查询关联表单
        handleSelectForm(index, item) {
            this.selectTableData = reactive(item.selectTableData)
            this.selectTableIndex = index
            this.page = 1
            this.pagesize = 10
            this.dialogFormName = ''
            this.dialogFormVisible = true
            this.handleGetFormData()
        },
        handleGetFormData() {
            this.$axios.get(`/form/formCustDialog/listData_PMcaidan?order=asc&offset=${this.page}&limit=${this.pagesize}&menu_name%5EVLK=${this.dialogFormName}`).then(res => {
                if (res.isOk) {
                    this.dialogTableData = res.rows
                    this.total = res.total
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        handleCurrentChange(val) {
            this.selectFormData = val
        },
        handleCommit() {
            this.dialogFormVisible = false
            let associatedForm = '', associatedFormUrl, associatedForm_uuid
            this.selectTableData.map(d => {
                associatedForm = (associatedForm ? associatedForm + ',' : '') + d.menu_name
                associatedFormUrl = (associatedFormUrl ? associatedFormUrl + ',' : '') + d.actionAddress
                associatedForm_uuid = (associatedForm_uuid ? associatedForm_uuid + ',' : '') + d.uuid
            })
            this.tableData[this.selectTableIndex].associatedForm = associatedForm
            this.tableData[this.selectTableIndex].associatedFormUrl = associatedFormUrl
            this.tableData[this.selectTableIndex].associatedForm_uuid = associatedForm_uuid
            this.tableData[this.selectTableIndex].selectTableData = this.selectTableData
        },
        // 查询角色
        getRoleData() {
            this.$axios.get(`/org/role/listJson?order=asc&offset=0&limit=10000&name_%5EVLK=&alias_%5EVLK=&enabled_%5EVLK=`).then(res => {
                if (res.isOk) {
                    const newData = res.rows
                    // 过滤启用状态&name不为空
                    this.roleList = newData.filter(d => { return d.enabled && d.name })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        handleSelectRole(val, index, item) {
            this.tableData[index].userOrTypeWork = val.name
            this.tableData[index].userOrTypeWorkId = val.id
        },
        handleSave() {
            if (!this.isSave) {
                this.$ElMessage({
                    message: `分项名称${this.form.selectShare}已存在！`,
                    type: 'error',
                })
                return
            }
            let isSaveJobName = true, isSaveUser = true, isSaveForm = true
            for (let d of this.tableData) {
                if (!d.jobName) {
                    isSaveJobName = false
                } else if (!d.userOrTypeWork) {
                    isSaveUser = false
                    break
                } else if (!d.associatedForm_uuid) {
                    isSaveForm = false
                    break
                }
            }
            if (!isSaveJobName) {
                this.$ElMessage({
                    message: '请输入任务名称',
                    type: 'error',
                })
                return
            }
            else if (!isSaveUser) {
                this.$ElMessage({
                    message: '请输入选择角色/工种',
                    type: 'error',
                })
                return
            }
            else if (!isSaveForm) {
                this.$ElMessage({
                    message: '请输入关联表单',
                    type: 'error',
                })
                return
            }
            const ppcgScheduleTemplateMaintenanceDtlList = this.tableData
            const param = {
                ppcgScheduleTemplateMaintenanceMst: {
                    distrName: this.form.selectDistr,
                    distrId: this.form.selectDistrId,
                    shareName: this.form.selectShare,
                    shareId: this.form.selectShareId,
                    ppcgScheduleTemplateMaintenanceDtlList,
                    createUser: localStorage.getItem('userName'),
                    createTime: this.$moment().format('YYYY-MM-DD HH:mm:ss')
                }
            }

            this.$axios.post(`/form/formDefData/saveData?key=ppcgScheduleTemplateMaintenanceMst&sql=`, param).then(res => {
                if (res.isOk) {
                    this.$ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
    }
}
</script>

<style scoped>
.labelTitle {
    margin-right: 1rem;
}
</style>